<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>商城后台</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" th:href="@{/lib/layui-v2.5.5/css/layui.css}" media="all">
    <link rel="stylesheet" th:href="@{/css/public.css}" media="all">
    <link rel="stylesheet" th:href="@{/lib/layui_ext/dtree/dtree.css}" >
    <link rel="stylesheet" th:href="@{/lib/layui_ext/dtree/font/dtreefont.css}" >
    <style>
        body {
            background-color: #ffffff;
        }
    </style>
</head>
<body>

<span th:replace="common_page::common"></span>

<div class="layui-form layuimini-form">
    <input type="hidden" name="id" id="id" th:value="${model.id}">
    <input type="hidden"  id="selectAreaCodes" th:value="${model.areaCodes}">
    <div class="layui-form-item">
        <label class="layui-form-label required">标题</label>
        <div class="layui-input-block">
            <input type="text" name="title" lay-verify="required" maxlength="100" lay-reqtext="不能为空" placeholder="请输入标题" th:value="${model.title}" class="layui-input">
            <tip>填写标题。</tip>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">点击跳转</label>
        <div class="layui-input-block">
            <input type="text" name="clickPath" lay-verify="required" maxlength="255" lay-reqtext="不能为空" placeholder="请输入点击跳转" th:value="${model.clickPath}"  class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">预览图</label>
        <div class="layui-input-block">
            <button type="button" class="layui-btn" id="uploadBannerImg">
                <i class="layui-icon">&#xe67c;</i>上传图片
            </button>
        </div>
        <input type="hidden" id="imgPath" name="imgPath" th:value="${model.imgPath}" >
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">预览</label>
        <div class="layui-input-block">
            <img  id="previewBannerImg" th:src="${model.httpImgPath}" th:width="240" th:height="220">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">开始展示时间</label>
        <div class="layui-input-block">
            <input type="text" id="startShowDate" name="startShowDate" class="layui-input" lay-verify="required" th:value="${model.startShowDateString}" readonly >
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">结束展示时间</label>
        <div class="layui-input-block">
            <input type="text" id="endShowDate" name="endShowDate" class="layui-input" lay-verify="required" th:value="${model.endShowDateString}" readonly >
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">显示状态</label>
        <div class="layui-input-block" th:if="${model.showStatus eq 1}">
            <select name="showStatus" lay-verify="required" lay-search="">
                <option value="1" selected>显示</option>
                <option value="0">隐藏</option>
            </select>
        </div>
        <div class="layui-input-block" th:if="${model.showStatus eq 0}">
            <select name="showStatus" lay-verify="required" lay-search="">
                <option value="1" >显示</option>
                <option value="0" selected>隐藏</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">位置</label>
        <div class="layui-input-block" th:if="${model.position eq 0}" >
            <input type="radio" name="position" value="0" title="门户首页" checked="">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">关联城市</label>
        <div class="layui-input-block">
            <input type="text" readonly  id="selectArea" lay-verify="required"  placeholder="请选择关联城市" th:value="${model.areaNames}" class="layui-input" >
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">排序</label>
        <div class="layui-input-block">
            <input type="number" name="bannerSort"    placeholder="请输入排序" th:value="${model.bannerSort}"  class="layui-input" lay-verify="number">
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">备注信息</label>
        <div class="layui-input-block">
            <textarea name="remark" class="layui-textarea" maxlength="255" th:text="${model.remark}" placeholder="请输入备注信息"></textarea>
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认保存</button>
        </div>
    </div>
</div>
<script th:src="@{/lib/layui-v2.5.5/layui.js}" charset="utf-8"></script>
<script>
    layui.config({
        base: basePath+'/lib/layui_ext/dtree/' //配置 layui 第三方扩展组件存放的基础目录
    }).extend({
        dtree: 'dtree' //定义该组件模块名
    }).use(['form','tree','dtree','upload','laydate'], function () {
        var form = layui.form,
            layer = layui.layer,
            $ = layui.$;

        var upload = layui.upload;
        var dtree = layui.dtree;
        var areaTree;
        var areaTreeDataArray = new Array();
        var areaArray =  new Array();
        var laydate = layui.laydate;

        var selectAreaCodes = $("#selectAreaCodes").val();
        if(selectAreaCodes!=null)
        {
            var selectAreaCodeArray =selectAreaCodes.split(",");
            if(selectAreaCodeArray!=null) {
                for (var i = 0; i < selectAreaCodeArray.length; i++) {
                    areaArray[i]={code:selectAreaCodeArray[i]};
                }
            }
        }



        //初始化时间控件
        laydate.render({
            elem: '#startShowDate' //指定元素
            ,type: 'datetime'
        });

        //初始化时间控件
        laydate.render({
            elem: '#endShowDate' //指定元素
            ,type: 'datetime'
        });

        //监听提交
        form.on('submit(saveBtn)', function (data) {

            if(data.field.imgPath==null||data.field.imgPath=="")
            {
                layer.msg("请上传轮播图");
                return false;
            }

            var areaCodeArray = new Array();
            for(var i=0;i<areaArray.length;i++)
            {
                areaCodeArray[i] = areaArray[i].code;
            }
            data.field.areaCodeArray=areaCodeArray;
            $.ajax({
                url:"[[@{/banner/update}]]",
                contentType: "application/json; charset=utf-8",
                type:'POST',
                data:JSON.stringify(data.field),
                success:function(data){
                    if(data.code<=0) {
                        layer.msg(data.msg);
                        return false;
                    }
                    var index = layer.alert(data.msg, {
                        title: '提示信息'
                    }, function () {
                        // 关闭弹出层
                        layer.close(index);
                        var iframeIndex = parent.layer.getFrameIndex(window.name);
                        parent.location.reload();
                        parent.layer.close(iframeIndex);

                    });
                }
            });
            return false;
        });


        /**
         * 拿到所有选中节点的ID
         * @param data
         * @param idArray
         */
        function getCheckdNodeId(data,idArray)
        {
            for(var i=0;i<data.length;i++)
            {
                areaTreeDataArray.push(data[i]);
                if(data[i].state.checked==true)
                {
                    idArray.push(parseInt(data[i].id));
                }
                if(data[i].children!=null&&data[i].children.length>0)
                {
                    getCheckdNodeId(data[i].children,idArray);
                }
            }
        }


        /**
         * 拿到指定节点对象
         */
        function getNodeObject(nodeId)
        {
            for(var i=0;i<areaTreeDataArray.length;i++)
            {
                if(areaTreeDataArray[i].id==nodeId)
                {
                    return areaTreeDataArray[i];
                }
            }
            return null;
        }


        /**
         * 拿到上级节点信息
         */
        function getParentNode(areaArray,areaNames,pid)
        {
            for(var i=0;i<areaTreeDataArray.length;i++)
            {

                if(areaTreeDataArray[i].id==pid)
                {
                    var exists=false;
                    //判断上级节点ID是否已经保存了
                    for(var j=0;j<areaArray.length;j++)
                    {
                        if(areaArray[j].id==pid) {
                            exists = true;
                        }
                    }
                    //避免上级节点ID重复保存两份
                    if(!exists)
                    {
                        areaArray.push({id:areaTreeDataArray[i].id,code:areaTreeDataArray[i].areaCode});
                        areaNames+=" "+areaTreeDataArray[i].text;
                    }
                    if(areaTreeDataArray[i].pid!=-1) {
                        //找到这个节点的上级节点
                        getParentNode(areaArray,areaNames, areaTreeDataArray[i].pid);
                    }
                }
            }
        }

        //执行实例
        var uploadInst = upload.render({
            elem: '#uploadBannerImg' //绑定元素
            ,url: '/banner/upload/img' //上传接口
            ,done: function(res){
                if(res.code==1)
                {
                    layer.msg(res.msg);
                }
                $("#previewBannerImg").attr("src",res.data.httpImgPath);
                $("#imgPath").val(res.data.imgPath);
            }
            ,error: function(){
                layer.msg("上传异常");
            }
        });

        $("#selectArea").click(function(){
            var bannerId = $("#id").val();
            loadding = layer.load();
            index = layer.open({
                title: '选择关联城市',
                type: 1,
                shade: 0.2,
                maxmin:true,
                area: ['20%', '60%'],
                btn: ['确定'],
                content: "<ul id='areaTree' class='dtree' data-id='0' ></ul>",
                success:function(layero){
                    loadding = layer.load();
                    $.ajax({
                        url:"[[@{/}]]banner/query/area/tree",
                        type:'POST',
                        data:{bannerId:bannerId},
                        success:function(data){
                            if(data.code==1)
                            {
                                //已选择节点
                                var idArray = new Array();
                                areaTreeDataArray = new Array();
                                getCheckdNodeId(data.data,idArray);
                                areaTree = dtree.render({
                                    elem: "#areaTree",//html中的id值
                                    data:data.data,
                                    width:'100%',
                                    checkbarType: "no-all",
                                    checkbar: true,  //开启复选框
                                    checkbarData: "choose",// 记录选中（默认）， "change"：记录变更， "all"：记录全部， "halfChoose"："记录选中和半选（V2.5.0新增）"
                                    done: function (res, $ul, first) {
                                        if (first) {
                                            if(idArray!=null&&idArray.length>0) {
                                                dtree.chooseDataInit("areaTree",  idArray.join(",")); //"001001,001002"被选中的子节点id
                                                dtree.initNoAllCheck("areaTree");// 反选半选状态(原始数据中父节点的选中或半选状态并没有被带上)
                                            }
                                        }

                                    }
                                });
                            }
                        },
                        complete:function()
                        {
                            layer.close(loadding);
                        }
                    });

                },
                yes: function(index, layero){
                    var selectNodes = areaTree.getCheckbarNodesParam("areaTree");
                    if(selectNodes==null||selectNodes.length<=0)
                    {
                        layer.msg("请选择地区");
                        return false;
                    }
                    areaArray =  new Array();
                    var areaNames = "";
                    for (var i = 0; i < selectNodes.length; i++) {
                        var selectNodeObject = getNodeObject(selectNodes[i].nodeId);
                        areaArray.push({id:selectNodeObject.id,code:selectNodeObject.code});
                        areaNames+=" "+selectNodeObject.text;
                        getParentNode(areaArray,areaNames,selectNodeObject.pid);
                    }
                    $("#selectArea").val(areaNames);
                    for (var j = 0; j < areaArray.length; j++) {
                        areaArray[j]={code:areaArray[j].code};
                    }
                    layer.close(index);
                }
            });
            $(window).on("resize", function () {
                layer.full(index);
            });

        });
    });
</script>
</body>
</html>